<?php

namespace model;

use root\base\model;
use common\extend\Check;

class admin_user extends model
{
	//登录判断用户名和密码
	public function findAdmin()
	{
		$db = $this->db();
		$where['username'] = $_POST['username'];
		$where['password'] = md5($_POST['password']);
		return $db->table('admin_user')->where($where)->find();
	}
	//将登录信息写入数据库
	public function loginDbInsert($userId)
	{
		$db = $this->db('admin_user');
		$where = ['id' => $userId];
		$updateDate = [
			'logintime' => date('Y-m-d H:i:s', time()),
			'loginip' => getip(),
		];
		return $db->where($where)->update($updateDate) ? true : $this->error($db->getError());
	}

	//查找一条信息
	public function findData()
	{
		$db = $this->db();
		$where['id'] = $_GET['id'];
		return $db->table('admin_user')->where($where)->find();
	}

	//判断用户名是否存在
	private function checkNameData()
	{
		$db = $this->db();
		if (empty($_POST['id'])) {
			$where['username'] = $_POST['username'];
		} else {
			//验证用户名是否存在 查询不等当前用户的数据进行比对
			$where = [
				'id <>' => $_GET['id'],
				'username' => $_POST['username'],
			];
		}
		return $db->table('admin_user')->where($where)->find();
	}
	//添加数据
	public function insertData()
	{
		//验证用户组名是否存在
		if ($this->checkNameData()) {
			return ['status' => 0, 'msg' => '用户组名已经存在！'];
		}
		//插入数据信息部分
		$db = $this->db('admin_user');
		$data = [
			'gid' => $_POST['gid'],
			'username' => varFilter($_POST['username']),
			'nickname' => varFilter($_POST['nickname']),
			'password' => md5(trim($_POST['password'])),
			'status' => $_POST['status'],
		];
		//验证数据
		$msg = Check::rule(
			[check::must($data['username']), '用户名不能为空'],
			[check::userName($data['username'], 4, 20), '用户名为4-20个字符的英文加字母，请检查'],
			[check::isChinese($data['nickname']), '真实姓名必须为中文，请检查'],
			[check::isPWD($_POST['password'], 6, 20), '密码为8-16位字符（英文/数字/符号）至少两种或下划线组合，请检查']
		);
		if ($msg !== true) {
			return ['status' => 0, 'msg' => $msg];
		} else {
			$re_key = $db->insert($data); //$this->error($db->getError());
			if ($re_key) {
				//写入日志
				insertSqlLog("添加用户：" . $_POST['username']);

				return ['key' => $re_key, 'status' => 1, 'msg' => '添加成功', 'cid' => $_POST['cid']];
			} else {
				return ['status' => 0, 'msg' => '数据错误！添加失败'];
			}
		}
	}
	//关联更新数据
	public function updateData()
	{
		//验证用户组名是否存在
		if ($this->checkNameData()) {
			return ['status' => 0, 'msg' => '用户组名已经存在！'];
		}
		$db = $this->db();
		$where['id'] = $_POST['id'];
		if (!empty($_POST['password'])) {
			$data = [
				'gid' => $_POST['gid'],
				'username' => varFilter($_POST['username']),
				'nickname' => varFilter($_POST['nickname']),
				'password' => md5(trim($_POST['password'])),
				'status' => $_POST['status'],
			];
			$msg = Check::rule(
				[check::must($data['username']), '用户名不能为空'],
				[check::userName($data['username'], 4, 20), '用户名为4-20个字符的英文加字母，请检查'],
				[check::isChinese($data['nickname']), '真实姓名必须为中文且不能空，请检查'],
				[check::isPWD($_POST['password'], 8, 16), '密码为8-16位字符（英文/数字/符号）至少两种或下划线组合，请检查']
			);
		} else {
			$data = [
				'gid' => $_POST['gid'],
				'username' => varFilter($_POST['username']),
				'nickname' => varFilter($_POST['nickname']),
				'status' => $_POST['status'],
			];
			$msg = Check::rule(
				[check::must($data['username']), '用户名不能为空'],
				[check::userName($data['username'], 4, 20), '用户名为4-20个字符的英文加字母，请检查'],
				[check::isChinese($data['nickname']), '真实姓名必须为中文且不能空，请检查']
			);
		}
		if ($msg !== true) {
			return ['status' => 0, 'msg' => $msg];
		} else {
			$re_key = $db->table('admin_user')->Where($where)->Update($data);
			if ($re_key) {
				//写入日志
				insertSqlLog("编辑用户：" . $_POST['username']);

				return ['status' => 1, 'msg' => '修改成功'];
			} else {
				return ['status' => 0, 'msg' => '数据没有变化'];
			}
		}
	}

	//用户自行修改密码
	public function passwordEdit()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		if (!empty($_POST['password'])) {
			$data = [
				'nickname' => varFilter($_POST['nickname']),
				'password' => md5(trim($_POST['password'])),
			];
			$msg = Check::rule(
				[check::isChinese($data['nickname']), '昵称必须为中文且不能空，请检查'],
				[check::isPWD($_POST['password'], 6, 20), '密码为8-16位字符（英文/数字/符号）至少两种或下划线组合，请检查']
			);
		} else {
			$data = [
				'nickname' => varFilter($_POST['nickname']),
			];
			$msg = Check::rule(
				[check::isChinese($data['nickname']), '昵称必须为中文且不能空，请检查']
			);
		}
		if ($msg !== true) {
			return ['status' => 0, 'msg' => $msg];
		} else {
			$re_key = $db->table('admin_user')->Where($where)->Update($data);
			if ($re_key) {
				//写入日志
				insertSqlLog("用户自行修改昵称和密码 ID：" . $_POST['id']);

				return ['status' => 1, 'msg' => '修改成功'];
			} else {
				return ['status' => 0, 'msg' => '数据没有变化'];
			}
		}
	}

	public function switchStatus()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		$data = [
			'status' => $_POST['status']
		];
		//写入日志
		insertSqlLog("切换用户状态 ID：" . $_POST['id']);
		return $db->table('admin_user')->where($where)->Update($data);
	}


	//删除一条数据
	public function deleteOneData()
	{
		$db = $this->db();
		$where['id'] = $_POST['id'];
		//写入日志
		insertSqlLog("删除用户：" . $_POST['id']);

		return $db->table('admin_user')->where($where)->Delete();
	}


	//获取数据并分页
	public function jsonPageSelect()
	{
		$db = $this->db();

		$where['a.id <>'] = 1;
		$p = intval($_GET['page'] ?? 0) ?: 1;
		$num = intval($_GET['limit'] ?? 0) ?: 10;

		$page = ['num' => $num, 'p' => $p, 'return' => true];

		//关联 article_cate 表查询  并设置 article_cate.id  别名 cateid             where IN a.cid(1,2,3)
		$field = 'b.id as groupid,b.groupname,a.id,a.gid,a.username,a.nickname,a.logintime,a.loginip,a.status';
		$join = 'LEFT JOIN admin_group b ON a.gid=b.id';

		$result['data'] = $db->table('admin_user a')->field($field)->where($where)->join($join)->Page($page)->order('a.id DESC')->select();
		$result['page'] = $db->getPage();

		return $result;
	}
}
